import PoolRoom from "../Entities/PoolRoom";
import DealRoom from "../Entities/DealRoom";
import PointRoom from "../Entities/PointRoom";
import LanguageMng from "./LanguageMng";
import GameWS from "./GameWS";
import GameDataUtilTs from "../Utils/GameDataUtilTs";
import GameLogicUtilTs from "../Utils/GameLogicUtilTs";
import RoomTypes from "../Static/RoomTypes";

cc.Class({
    extends: cc.Component,

    properties: {
        declareNode:{
            default:null,
            type:cc.Node
        },

        gotoDealInfoBtn:{
            default:null,
            type:cc.Node
        },

        bgParent:{
            default:null,
            type:cc.Node
        },

        btnParent:{
            default:null,
            type:cc.Node
        },

        dragBlocker:{
            default:null,
            type:cc.Node
        },

        finishSlotNode:{
            default:null,
            type:cc.Node
        },

        windowParent:{
            default:null,
            type:cc.Node
        },

        windowBlockBg:{
            default:null,
            type:cc.Node
        },

        discardStack:{
            default:null,
            type:require("DisPokerStack")
        },

        _showFinishIndicator:false,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.node.on("ui_update_top_info",this._onUpdateTopInfo.bind(this),this)
        this.node.on("ui_update_top_info_prize",this.onUpdateTopBarPrize.bind(this),this)
        this.node.on("game_user_ready_change",this._onGameUserReadyChange.bind(this),this)
        this.node.on("user_coin_changed",this._onUserCoinChanged.bind(this),this)

        this.node.on("ui_user_off_line",this._onUIUserOffLine.bind(this),this)
        this.node.on("ui_user_on_line",this._onUIUserOnLine.bind(this),this)
        this.node.on("ui_user_leave",this._onUIUserLeave.bind(this),this)
        this.node.on("ui_user_destroy",this._onUIUserOut.bind(this),this)

        this.node.on("ui_init_seat_user",this._onUpdateSeatUser.bind(this),this)
        this.node.on("ui_update_seat_user",this._onUpdateSeatUser.bind(this),this)
        this.node.on("ui_update_seat_pts",this._onUpdateSeatScore.bind(this),this)
        this.node.on("ui_show_btn_group",this._onUIShowBtnGroup.bind(this),this)
        this.node.on("ui_show_btn_discard",this._onUIShowBtnDiscard.bind(this),this)
        this.node.on("ui_show_score",this._showDealInfo.bind(this),this)
        this.node.on("ui_hide_score",this._hideDealInfo.bind(this),this)
        this.node.on("ui_show_btn_declare",this._onUIShowBtnDeclare.bind(this),this)

        this.node.on("ui_show_btn_ready",this.showBtnReady.bind(this),this)
        this.node.on("ui_show_reconnect_button",this._onUIShowReconnectButton.bind(this),this)
        this.node.on("ui_show_btn_close_guild",this._onUIShowBtnCloseGuild.bind(this),this)
        this.node.on("ui_show_btn_deals",this._onUIShowBtnDeal.bind(this),this)
        this.node.on("ui_close_deal_info",this._onUICloseDealInfo.bind(this),this)
        this.node.on("ui_init_deal_info_board",this._onUIInitDealInfoBoard.bind(this),this)
        // this.node.on("ui_update_deal_info_board",this._onUIUpdateDealInfoBoard.bind(this),this)
        this.node.on("ui_update_dealinfo_scores",this._onUIUpdateDealInfoScores.bind(this),this)
        this.node.on("ui_update_dealinfo_cards",this._onUIUpdateDealInfoCards.bind(this),this)
        this.node.on("ui_update_dealinfo_winner",this._onUIUpdateDealinfoWinnder.bind(this),this)

        this.node.on("ui_clear_deal_board",this._onUIClearDealBoard.bind(this),this)

        this.node.on("ui_show_view_node",this._onUIShowGotoDealinfo.bind(this),this)
        this.node.on("ui_game_count_down_start",this._onGameCountDownStart.bind(this),this)
        this.node.on("ui_show_more_help",this._hideHelpNode.bind(this),this)
        this.node.on("ui_show_drag_blocker",this._onUIShowDragBlocker.bind(this),this)
        this.node.on("ui_show_finish_indicator",this.showFinishIndicator.bind(this),this)


        this.node.on("ui_show_deal_waitting_string",this._onUIShowDealWaittingString.bind(this),this)
        this.node.on("ui_hide_deal_waitting_string",this._onUIHideDealWaittingString.bind(this),this)

        this.dragBlocker.active = false
        this.gameMgr = cc.find("Canvas").getComponent("GameMgrBase")
    },

    start(){
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(cc.gg.dataMgr.room){
                this.initTopBar()
                return true
            }
            return false
        }.bind(this))
    },

    showDisStackNotice(show,pokerValue){
        if(show && this._showFinishIndicator) return
        this.discardStack.showDiscardNotice(show,pokerValue)
    },

    _onUIClearDealBoard:function () {
        if(!this.dealBoardNode)
            this.dealBoardNode = cc.find("Canvas/GameMenu/DealBoard")

        this.dealBoardNode.getComponent("DealBoardSv").clearDealBoard()
    },

    async _onUIUpdateDealinfoWinnder (id) {
        await this._getDealInfoScript(function (dealInfo) {
            cc.gg.gameDataUtil.setDealInfoWinner(id)
            dealInfo.setWinUser(id)
        })
    },

    showFinishIndicator:function (show, frame) {
        this._showFinishIndicator = show
        if(show){
            this.finishSlotNode.getComponent("FinishSlot").showIndicator(frame)
            this.showDisStackNotice(false,null)
        }
        else
            this.finishSlotNode.getComponent("FinishSlot").hideIndicator()
    },

    async _onUIUpdateDealInfoCards (id, cards) {
        await this._getDealInfoScript(function (dealInfo) {
            dealInfo.updateUserCards(id,cards)
        })
    },

    async _onUIUpdateDealInfoScores (id,score,totalScore,showScore) {
        await this._getDealInfoScript(function (dealInfo) {

            cc.gg.gameDataUtil.setDealInfoScore(id,score)
            let totalScoreStr = !showScore?cc.gg.gameDataUtil.getStringOfRupee(totalScore):totalScore
            cc.gg.gameDataUtil.setDealInfoTotalScore(id,totalScoreStr)
            dealInfo.updateUserScores(id,score,totalScoreStr)
        })
    },

    _onUIShowDragBlocker:function (show) {
        if(this.dragBlocker.active != show) this.dragBlocker.active = show
    },

    _onUIHideDealWaittingString:function () {
        if(this.gameWaitNoticeNode){
            this.gameWaitNoticeNode.destroy()
        }
    },

    _onUIShowDealWaittingString:function (string) {
        if(this.gameWaitNoticeNode){
            this.gameWaitNoticeNode.destroy()
        }
        cc.loader.loadRes("notice/GameWaitNotice",cc.Prefab,function (err, prefab) {
            let newNode = cc.instantiate(prefab)
            this.gameWaitNoticeNode = newNode
            this.gameWaitNoticeNode.name = "GameWaitNotice"
            cc.find("Canvas/Windows").addChild(newNode)
            newNode.getComponent("GameWaitNotice").showGameWaitNotice(string)
        }.bind(this))
    },

    onUpdateTopBarPrize:function (prize1, prize2) {
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(this._addedTopBar){
                let topBarNode = this.getTopBar()
                let topBarScript = topBarNode.getComponent("TopInfoBar")
                topBarScript.updateTopInfoPrizes(prize1,prize2)
                return true
            }
            return false
        }.bind(this))
    },

    //仅仅add上，等第一次更新的时候，动画出来
    initTopBar:function () {
        if(this._addedTopBar){
            cc.warn("已经有了topbar了")
            return
        }

        let topBarName = "top_bar_node"
        let topBarParent = this.bgParent

        let prefabName = ""
        let nowRoom = cc.gg.dataMgr.room
        if(nowRoom instanceof PointRoom){
            prefabName = "uis/TopInfoPoints"
        }else if(nowRoom instanceof PoolRoom){
            prefabName = "uis/TopInfoPool"
        }else if(nowRoom instanceof DealRoom){
            prefabName = "uis/TopInfoDeal"
        }else {
            prefabName = "uis/TopInfoPoints"
        }

        // if(!GameLogicUtilTs.wantEnterRoomType){
        //     let nowRoom = cc.gg.dataMgr.room
        //     if(nowRoom instanceof PointRoom){
        //         prefabName = "uis/TopInfoPoints"
        //     }else if(nowRoom instanceof PoolRoom){
        //         prefabName = "uis/TopInfoPool"
        //     }else if(nowRoom instanceof DealRoom){
        //         prefabName = "uis/TopInfoDeal"
        //     }else {
        //         prefabName = "uis/TopInfoPoints"
        //     }
        // }else {
        //     if(GameLogicUtilTs.wantEnterRoomType === RoomTypes.POINTS){
        //         prefabName = "uis/TopInfoPoints"
        //     }else if(GameLogicUtilTs.wantEnterRoomType === RoomTypes.POOL){
        //         prefabName = "uis/TopInfoPool"
        //     }else if(GameLogicUtilTs.wantEnterRoomType === RoomTypes.DEAL){
        //         prefabName = "uis/TopInfoDeal"
        //     }else {
        //         prefabName = "uis/TopInfoPoints"
        //     }
        // }
        // GameLogicUtilTs.wantEnterRoomType = null

        cc.loader.loadRes(prefabName,cc.Prefab,function (err, prefab) {
            if(err){
                cc.error(err)
                return
            }
            this._addedTopBar = true
            let newNode = cc.instantiate(prefab)
            newNode.name = topBarName
            topBarParent.addChild(newNode)

            newNode.x = 0
            newNode.y = cc.winSize.height/2 + newNode.height/2

            newNode.runAction(cc.moveBy(0.2,0,-newNode.height))
        }.bind(this))
    },

    getIsTopBarReady:function () {
        return this._addedTopBar
    },

    changeOptionStateUI:function (state) {
        let optionUIs = this.optNode.getComponent("OptionUIs")
        if(state === cc.gg.enumConfig.OptionState.DISPATCHING){
            optionUIs.btnDrop.active = false
            optionUIs.btnDiscard.active = false
            optionUIs.btnFinish.active = false
        }else if(state === cc.gg.enumConfig.OptionState.WAIT){
            optionUIs.btnDrop.active = false
            optionUIs.btnDiscard.active = false
            optionUIs.btnFinish.active = false
        }else if(state === cc.gg.enumConfig.OptionState.GRAB){
            optionUIs.btnDrop.active = true
            optionUIs.btnDiscard.active = false
            optionUIs.btnFinish.active = false
        }else if(state === cc.gg.enumConfig.OptionState.PLAY){
            optionUIs.btnDrop.active = false
        }else if(state === cc.gg.enumConfig.OptionState.CALCULATING){
            optionUIs.btnDrop.active = false
            optionUIs.btnDiscard.active = false
            optionUIs.btnFinish.active = false
        }

        if(cc.gg.dataMgr.playGuild){
            optionUIs.btnDrop.active = false
        }
    },

    getTopBar:function () {
        return this.bgParent.getChildByName("top_bar_node")
    },

    _onGameCountDownStart:function (countTime) {

        let waitNoticeNode = cc.find("Canvas/Windows/GameWaitNotice")
        if(waitNoticeNode && cc.isValid(waitNoticeNode,true)) waitNoticeNode.destroy()

        if(cc.isValid(this.gameCountDownNode,true)){
            this.gameCountDownNode.getComponent("GameCountDown").startGameCountDown(countTime)
        }else{
            cc.loader.loadRes("notice/GameCountDown",cc.Prefab,function (err, prefab) {
                if(err){
                    cc.error(err)
                    return
                }

                let newNode = cc.instantiate(prefab)
                cc.find("Canvas/Windows").addChild(newNode)
                newNode.getComponent("GameCountDown").startGameCountDown(countTime)
                this.gameCountDownNode = newNode

                cc.loader.releaseRes("notice/NetWait")
            }.bind(this))
        }
    },



    _onGameCountDownUpdate:function (countTime) {
        let waitNoticeNode = cc.find("Canvas/Windows/GameWaitNotice")
        if(waitNoticeNode && cc.isValid(waitNoticeNode,true)) waitNoticeNode.destroy()

        if(this._addedGameCountDown && cc.isValid(this.gameCountDownNode,true)){
            this.gameCountDownNode.getComponent("GameCountDown").updateGameCountDown(countTime)
        }else if(!this._addedGameCountDown){
            this._addedGameCountDown = true
            cc.loader.loadRes("notice/GameCountDown",cc.Prefab,function (err, prefab) {
                if(err){
                    cc.error(err)
                    return
                }

                let newNode = cc.instantiate(prefab)
                cc.find("Canvas/Windows").addChild(newNode)
                newNode.getComponent("GameCountDown").updateGameCountDown(countTime)
                this.gameCountDownNode = newNode

                cc.loader.releaseRes("notice/NetWait")
            }.bind(this))
        }
    },

    _onUIShowGotoDealinfo:function (isShow) {
        this.gotoDealInfoBtn.active = isShow
    },

    // _onUIUpdateDealInfoBoard:function (userObj) {
    //     cc.log("report、commit接口：使用userObj更新DealInfo：",userObj)
    //     this.dealInfoNode.getComponent("DealInfo")._onUpdateDealInfo(userObj,cc.gg.dataMgr.getMixCardNum())
    // },

    async _onUIInitDealInfoBoard (id,cards,showScoreWhenWaiting) {
        let mixNum = cc.gg.dataMgr.getMixCardNum()

        await this._getDealInfoScript(function (dealInfo) {
            cc.gg.gameDataUtil.initDealInfoData(cc.gg.dataMgr.users,showScoreWhenWaiting)
            dealInfo.initDealInfo(cc.gg.gameDataUtil.dealInfoData,mixNum,showScoreWhenWaiting)
            if(id && cards && cards.length)
                dealInfo.updateUserCards(id,cards,mixNum)
        })
    },

    async _getDealInfoScript (cb) {
        if(GameDataUtilTs.isKickCauseNoMoney) return null

        if(this._loadingDealInfoPrefab){
            cc.find("Canvas").emit("msgwatcher_add",function () {
                if(this.dealInfoScript){
                    if(cb) cb(this.dealInfoScript)
                    return true
                }
                return false
            }.bind(this))
            return null
        }

        if(!this.dealInfoScript){
            this._loadingDealInfoPrefab = true
            let dealInfoPrefab = await cc.gg.resUtil.loadRes("windows/DealInfo")
            this._loadingDealInfoPrefab = false
            let newNode = cc.instantiate(dealInfoPrefab)
            this.windowParent.addChild(newNode)
            this.dealInfoScript = newNode.getComponent("DealInfo")
            newNode.active = false
            this.setDealInfoShown(false)

            // let gameMgr = cc.find("Canvas").getComponent("GameMgrBase")
            this.dealInfoScript.initDealInfoData(this.gameMgr)
        }

        if(cb) cb(this.dealInfoScript)
        return this.dealInfoScript
    },

    async _onUICloseDealInfo () {
        this._hideDealInfo()
        // cc.gg.emitEvent("dealinfo_count_down_finish")

        // this._dealInfoShown = false
        // let dealInfo = await this._getDealInfoScript()
        // dealInfo.hideDealInfo()
    },

    _onUIShowBtnDeal:function (isShow) {
        cc.find("Canvas/Buttons/BtnRecords").active = isShow
    },

    _onUIShowBtnCloseGuild:function (isShow) {
        let closeBtnNode = cc.find("Canvas/BtnCloseGuild")
        if(closeBtnNode) closeBtnNode.active = isShow
    },

    _onUIShowBtnDeclare:function (isShow) {
        this.declareNode.active = isShow
    },

    _onUIShowReconnectButton:function (isShow) {
        cc.find("Canvas/Buttons/BtnReconnect").active = isShow
    },

    showBtnReady:function (isShow) {
        cc.find("Canvas/Buttons/BtnReady").active = isShow
    },

    _onUIShowBtnDiscard:function (isShow) {
        this.optNode.getComponent("OptionUIs").btnDiscard.active = isShow
        this.optNode.getComponent("OptionUIs").btnFinish.active = isShow
    },

    _onUIShowBtnGroup:function (isShow) {
        this.optNode.getComponent("OptionUIs").btnGroup.active = isShow
    },

    _onUpdateSeatScore:function () {
        for(let i in cc.gg.dataMgr.users){
            let userObj = cc.gg.dataMgr.users[i]
            if(userObj.id === cc.gg.dataMgr.getPlayerGameId()){
                cc.gg.tpgMgr.playerSeat.getComponent("TPPHead").updateGameScore(userObj.score)
            }else {
                let seat = cc.gg.tpgMgr.getSeatByUID(userObj.id)
                if(!seat) seat = cc.gg.tpgMgr.getEmptySeat()
                seat.getComponent("SeatOther").updateGameScore(userObj.score)
            }
        }
    },

    _onUpdateSeatUser:function (userObj,noAnim) {
        cc.log("玩家进入UI")
        if(userObj.id === cc.gg.dataMgr.getPlayerUser().id){
            cc.gg.tpgMgr.playerSeat.getComponent("TPPHead").initTPPHead(userObj)
        }else {
            let seat = cc.gg.tpgMgr.getSeatByUID(userObj.id)
            if(!seat){
                // seat = cc.gg.tpgMgr.getEmptySeat()
                seat = cc.gg.tpgMgr.getSeatByUserIdx(cc.gg.dataMgr.getPlayerUser().seat_no,userObj.seat_no)
                if(!seat){
                    this.sendDebugNoEmptySeat(null,userObj)
                    return
                }
                if(noAnim){
                    seat.getComponent("SeatOther").initSeat(userObj)
                }else {
                    seat.getComponent("SeatOther").enterUser(userObj)
                }
            }else {
                seat.getComponent("SeatOther").initSeat(userObj)
            }
        }
    },

    // getSeatByIdx(){
    //     if(cc.gg.dataMgr.playGuild) return cc.gg.tpgMgr.opponentSeatParent.children[0]
    //
    //     for(let i=0;i<cc.gg.tpgMgr.opponentSeatParent.children.length;i++){
    //         let script = cc.gg.tpgMgr.opponentSeatParent.children[i].getComponent("SeatOther")
    //         if(!script.playerInfo) continue
    //         if(script.playerInfo.id === id)
    //             return cc.gg.tpgMgr.opponentSeatParent.children[i]
    //     }
    //
    //     return null
    // },

    sendDebugNoEmptySeat(event,userObj){
        userObj = userObj || cc.gg.dataMgr.getPlayerUser()
        let userCount = cc.gg.baseUtil.getMapLength(cc.gg.dataMgr.users)
        let idList = ""
        for(let key in cc.gg.dataMgr.users){
            let o = cc.gg.dataMgr.users[key]
            idList += o.id.toString() + ","
        }
        let kv = {
            keys:["AvatarCount","TarUserId","IdList"],
            values:[userCount.toString(),userObj.id.toString(),idList]
        }
        let jsonStr = JSON.stringify(kv)
        cc.gg.tdUtil.doSendTdEvent("debug_no_empty_seat","",jsonStr)
    },

    _onUIUserOffLine:function (id) {
        if(id !== cc.gg.dataMgr.getPlayerId()){
            let seatNode = cc.gg.tpgMgr.getSeatByUID(id)
            seatNode.getComponent("SeatOther").changeNet(false)
        }
    },

    _onUIUserOnLine:function (id) {
        if(id !== cc.gg.dataMgr.getPlayerId()){
            let seatNode = cc.gg.tpgMgr.getSeatByUID(id)
            seatNode.getComponent("SeatOther").changeNet(true)
        }
    },

    _onUIUserOut:function (id) {
        if(id !== cc.gg.dataMgr.getPlayerId()){

            let seatNode = cc.gg.tpgMgr.getSeatByUID(id)
            if(!seatNode){
                cc.warn("找不到uid为",id,"的座位")
                return
            }

            seatNode.getComponent("SeatOther").userOut()
        }
    },

    _onUIUserLeave:function (id) {
        if(id !== cc.gg.dataMgr.getPlayerId()){

            let seatNode = cc.gg.tpgMgr.getSeatByUID(id)
            if(!seatNode){
                cc.warn("找不到uid为",id,"的座位")
                return
            }

            // seatNode.getComponent("TPPHead").updateGameScore(newScore)

            seatNode.getComponent("SeatOther").changeToLeave()
        }
    },

    _onUserCoinChanged:function (userId, newCoin) {
        let seatNode = cc.gg.tpgMgr.getSeatByUID(userId)
        if(userId === cc.gg.dataMgr.getPlayerGameId()) seatNode.getComponent("TPPHead").changeCoin(newCoin)
        else{
            // seatNode.getComponent("SeatOther").changeCoin(newCoin)
        }
    },

    _onFlowStartGame:function () {
        this.showBtnReady(false)
    },

    _onGameUserReadyChange:function (id, bState) {
        let seatScript = null
        let ready = bState == cc.gg.enumConfig.ReadyState.READY

        if(id === cc.gg.dataMgr.getPlayerGameId()){
            cc.find("Canvas/Buttons/BtnReady/Label").getComponent(cc.Label).string = ready ? LanguageMng.getSentence(145) : LanguageMng.getSentence(145)
            seatScript = cc.gg.tpgMgr.playerSeat.getComponent("TPPHead")
        }else {
            seatScript = cc.gg.tpgMgr.getSeatByUID(id).getComponent("SeatOther")
        }

        if(bState === cc.gg.enumConfig.ReadyState.READY){
            seatScript._setFaceWhite()
            seatScript.changeReadyState(ready)
        }else if(bState === cc.gg.enumConfig.ReadyState.ELIMINATED){
            seatScript.changeToEliminated()
        }else if(bState === cc.gg.enumConfig.ReadyState.DROPED){
            seatScript.changeToDrop()
        }else {
            seatScript._setFaceWhite()
        }
    },

    // update (dt) {},

    onUIButtonsClicked:function (event) {
        let btnName = event.target.name
        if(btnName === "BtnSetting"){
            cc.gg.tdUtil.doSendTdEvent("click_game_menu","Table")
            this._showGameMenu()
        }else if(btnName === "MenuBlockBg"){
            this._hideGameMenu()
        }else if(btnName === "BtnBackToLobby"){
            cc.gg.tdUtil.doSendTdEvent("click_game_menu_quit","Table")
            this._hideGameMenu()
            if(cc.gg.dataMgr.playGuild){
                cc.gg.dataMgr.playGuild = false
                cc.gg.gameDataUtil.goToLobby(true)
            }else {

                let cbYes = function () {
                    let kv = {
                        keys:["BackToLobby"],
                        values:[cc.gg.enumConfig.BackToLobbyOpt.CONFIRM]
                    }
                    let jsonStr = JSON.stringify(kv)
                    cc.gg.tdUtil.doSendTdEvent("game_quit","GameMenu",jsonStr)
                }
                let cbCancel = function () {
                    let kv = {
                        keys:["BackToLobby"],
                        values:[cc.gg.enumConfig.BackToLobbyOpt.CANCEL]
                    }
                    let jsonStr = JSON.stringify(kv)
                    cc.gg.tdUtil.doSendTdEvent("game_quit","GameMenu",jsonStr)
                }
                let cbDirectory = function () {
                    let kv = {
                        keys:["BackToLobby"],
                        values:[cc.gg.enumConfig.BackToLobbyOpt.DIRECTORY]
                    }
                    let jsonStr = JSON.stringify(kv)
                    cc.gg.tdUtil.doSendTdEvent("game_quit","GameMenu",jsonStr)
                }
                this.gameMgr.backToLobby(cbYes,cbCancel,cbDirectory)
            }
        }else if(btnName === "BtnBackToGame"){
            cc.gg.tdUtil.doSendTdEvent("click_game_dealinfo_backtogame","Table")
            cc.gg.emitEvent("dealinfo_count_down_finish")
            this._hideDealInfo()
        }else if(btnName === "BtnMenuSetting"){
            cc.gg.tdUtil.doSendTdEvent("click_game_menu_setting","Table")
            this._hideGameMenu()
            this._showSetting()
        }else if(btnName === "BtnSettingClose"){
            this._hideSetting()
        }else if(btnName === "BtnInformation"){
            cc.gg.tdUtil.doSendTdEvent("click_game_menu_information","Table")
            this._hideGameMenu()
            this._showInformation()
        }else if(btnName === "BtnScore"){
            cc.gg.tdUtil.doSendTdEvent("click_game_menu_score","Table")
            this._hideGameMenu()
            this._showDealInfo(true)
        }else if(btnName === "BtnDealInfoClose"){
            cc.gg.emitEvent("dealinfo_count_down_finish")
            this._hideDealInfo()
        }else if(btnName === "BtnHelp"){
            cc.gg.tdUtil.doSendTdEvent("click_game_menu_help","Table")
            this._hideGameMenu()
            this._showHelp()
        }else if(btnName === "BtnHelpClose"){
            this._hideHelpNode()
        }else if(btnName === "BtnReady"){
            cc.find("Canvas").emit("option_player_ready")
        }else if(btnName === "BtnReconnect"){
            // cc.find("Canvas").emit("game_start_reconnect")
        }else if(btnName === "BtnCloseGuild"){
            cc.gg.tdUtil.doSendTdEvent("click_game_close_guild","Table")
            cc.gg.dataMgr.playGuild = false
            cc.gg.dataMgr.setPlayerInfo(null)
            cc.find("Canvas").emit("game_close_guild")
        }else if(btnName === "BtnRecords"){
            cc.gg.tdUtil.doSendTdEvent("click_game_dealboard","Table")
            this._showDealBoard()
        }else if(btnName === "BtnCloseDealBoard"){
            this._hideDealBoard()
        }else if(btnName === "disconnect"){
            GameWS.disconnect()
        }
    },

    _showDealBoard:function () {
        if(!this.dealBoardNode)
            this.dealBoardNode = cc.find("Canvas/GameMenu/DealBoard")

        if(this.dealBoardNode.active){
            return
        }

        this._hideDealInfo()
        this.dealBoardNode.active = true
        this.windowEnterFromTop(this.dealBoardNode)
        this.dealBoardNode.getComponent("DealBoardSv").refreshDealBoardSv()
    },

    _hideDealBoard:function () {
        if(!this.dealBoardNode)
            this.dealBoardNode = cc.find("Canvas/GameMenu/DealBoard")

        if(!this.dealBoardNode.active){
            return
        }
        this.dealBoardNode.active = false
        this.windowOutToBottom(this.dealBoardNode)
    },

    _showHelp:function () {
        cc.find("Canvas/GameMenu/MenuBlockBg").active = true
        // let infoNode = cc.find("Canvas/GameMenu/HelpNode")

        cc.loader.loadRes("windows/MoreHelp",cc.Prefab,function (err, prefab) {
            let newNode = cc.instantiate(prefab)
            newNode.width = cc.winSize.width
            newNode.height = cc.winSize.height

            let infoNode = cc.find("Canvas/Windows")
            infoNode.addChild(newNode)
            this.helpNode = newNode
            this.windowEnterFromTop(newNode)
        }.bind(this))
    },

    _hideHelpNode:function () {
        this.windowBlockBg.active = false
        let infoNode = this.helpNode
        this.windowOutToBottomAndDestroy(infoNode)
    },

    async _showDealInfo (showCloseBtn) {
        await this._getDealInfoScript(function (dealInfo) {
            this._hideDealBoard()
            dealInfo.setDealInfoCloseStatus(showCloseBtn)

            if(this._dealInfoShown){
                return
            }
            this.setDealInfoShown(true)

            this.windowBlockBg.active = true
            if(!dealInfo._inited){
                let isPointRoom = cc.gg.dataMgr.room instanceof PointRoom
                cc.gg.gameDataUtil.initDealInfoData(cc.gg.dataMgr.users,!(isPointRoom&&cc.gg.gameDataUtil.getShowRupee()))
                dealInfo.initDealInfo(cc.gg.gameDataUtil.dealInfoData,cc.gg.dataMgr.getMixCardNum())
            }
            dealInfo.showDealInfo()
        }.bind(this))
    },

    setDealInfoShown:function (shown) {
        this._dealInfoShown = shown
        // cc.error("将showen设置为：",shown)
    },

    // _loadDealInfo:function (cb) {
    //     if(this.__loadingDealInfo)
    //         return
    //
    //     this.__loadingDealInfo = true
    //     cc.loader.loadRes("windows/DealInfo",cc.Prefab,function (err, prefab) {
    //         this.__loadingDealInfo = false
    //         if(err){
    //             cc.error(err)
    //             return
    //         }
    //
    //         let dealInfo = cc.instantiate(prefab)
    //         cc.find("Canvas/GameMenu").addChild(dealInfo)
    //         this.dealInfoNode = dealInfo
    //         if(cb) cb(this.dealInfoNode)
    //     }.bind(this))
    // },

    async _hideDealInfo () {
        // cc.log("================隐藏dealInfo！",this._dealInfoShown)
        if(!this._dealInfoShown) return
        this.setDealInfoShown(false)

        this.windowBlockBg.active = false

        await this._getDealInfoScript(function (dealInfo) {
            dealInfo.hideDealInfo()
            dealInfo.stopCountDown()
        })
        // if(this.dealInfoNode.active){
        //     this.windowOutToBottom(this.dealInfoNode)
        // }
    },

    async _showInformation () {
        if(this._informationShown) return
        this._informationShown = true

        this.windowBlockBg.active = true

        if(!this.gameInformation){
            let prefab = await cc.gg.resUtil.loadRes("windows/GameInformation")
            let infoNode = cc.instantiate(prefab)
            this.windowParent.addChild(infoNode)

            let info = infoNode.getComponent("GameInformation")
            this.gameInformation = info
        }

        // let deckNum = Math.floor((cc.gg.dataMgr.room.t_size+1)/2)
        let playerCount = cc.gg.dataMgr.room.t_size
        let deckNum = 1
        if(playerCount === 2){
            deckNum = 1
        }else {
            deckNum = 2
        }
        this.gameInformation.initGameInformation(this,cc.gg.dataMgr.room.id,cc.gg.dataMgr.room.room_id,cc.gg.dataMgr.room.multi,deckNum)
        this.gameInformation.showInformation()
    },

    _hideInformation:function () {
        if(!this._informationShown) return
        this._informationShown = false

        this.windowBlockBg.active = false
        this.gameInformation.hideInformation()
    },

    async _showSetting () {
        if(this._settingShown) return
        this._settingShown = true

        this.windowBlockBg.active = true

        if(!this.setting){
            let prefab = await cc.gg.resUtil.loadRes("windows/Setting")
            let settingNode = cc.instantiate(prefab)

            this.windowParent.addChild(settingNode)
            this.setting = settingNode.getComponent("Setting")
            this.setting.initSetting(this)
        }

        this.setting.showGameSetting()
    },

    _hideSetting:function () {
        if(!this._settingShown) return
        this._settingShown = false

        this.windowBlockBg.active = false
        this.setting.hideGameSetting()
    },

    _showGameMenu:function () {
        let blockBg = cc.find("Canvas/GameMenu/MenuBlockBg")
        blockBg.active = true
        let menuNode = cc.find("Canvas/GameMenu/Menu")
        menuNode.active = true
        menuNode.x = cc.winSize.width/2
        menuNode.runAction(cc.moveBy(0.2,-menuNode.width,0))
    },

    _hideGameMenu:function () {
        let blockBg = cc.find("Canvas/GameMenu/MenuBlockBg")
        blockBg.active = false
        let menuNode = cc.find("Canvas/GameMenu/Menu")
        let seq = cc.sequence(cc.moveBy(0.2,menuNode.width,0),cc.callFunc(function () {
            menuNode.active = false
        }.bind(this),this))
        menuNode.runAction(seq)
    },

    windowEnterFromTop:function (node) {
        node.stopAllActions()
        node.active = true
        node.x = 0
        node.y = cc.winSize.height/2 + node.height
        node.runAction(cc.moveBy(0.12,0,-cc.winSize.height/2-node.height/2))
    },

    windowOutToBottom:function (node) {
        node.active = true
        node.x = 0
        let seq = cc.sequence(cc.moveTo(0.12,0,-cc.winSize.height/2),
            cc.callFunc(function () {
                this.active = false
            }.bind(node),this))
        node.runAction(seq)
    },

    windowOutToBottomAndDestroy:function (node) {
        node.active = true
        node.x = 0
        let seq = cc.sequence(cc.moveTo(0.12,0,-cc.winSize.height/2),
            cc.callFunc(function () {
                this.destroy()
            }.bind(node),this))
        node.runAction(seq)
    },

    _onUpdateTopInfo:function (roomId, roomType, roomBet, prize) {
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(this._addedTopBar){
                cc.log("update TopBar：",roomId,roomType,roomBet,prize)
                let topBarNode = this.getTopBar()
                let topBarScript = topBarNode.getComponent("TopInfoBar")
                topBarScript.updateTopInfo(roomId,roomType,roomBet,prize)
                return true
            }
            return false
        }.bind(this))
    },

   initTopInfo:function (roomId, roomType, roomBet) {
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(this._addedTopBar){
                let topBarNode = this.getTopBar()
                let topBarScript = topBarNode.getComponent("TopInfoBar")
                topBarScript.initTopInfo(roomId,roomType,roomBet)
                return true
            }
            return false
        }.bind(this))
    },

    updateTopPrize:function (prizeThumbNum) {
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(this._addedTopBar){
                let topBarNode = this.getTopBar()
                let topBarScript = topBarNode.getComponent("TopInfoBar")
                topBarScript.updatePrizeThumb(prizeThumbNum)
                return true
            }
            return false
        }.bind(this))
    },
});
